//
//  BDChatSettingViewController.m
//  BadBoy
//
//  Created by wen on 2017/6/7.
//  Copyright © 2017年 com.8xiong. All rights reserved.
//

#import "BDChatSettingViewController.h"
#import "BDChatSetTableViewCell.h"
#import "BDUserInfoViewController.h"
#import "LPActionSheet.h"
#import "BDGroupChooseViewController.h"
#import "BDComplaintsViewController.h"

@interface BDChatSettingViewController ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *datasource;

@property (nonatomic, assign) BOOL isZhiding;
@property (nonatomic, assign) BOOL isMiandarao;

@end

@implementation BDChatSettingViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = ASLocalizedString(@"聊天设置");
    
    NSString *zhidingSearchPath = [DocumentPath stringByAppendingPathComponent:@"zhidingSearch.plist"];
    NSMutableArray *array = [NSMutableArray arrayWithContentsOfFile:zhidingSearchPath];
    if ([array containsObject:((JMSGUser *)_conversation.target).username]) {
        self.isZhiding = YES;
    }else{
        self.isZhiding = NO;
    }
    
    self.isMiandarao = ((JMSGUser *)_conversation.target).isNoDisturb;
    
    [self requestDatasource];
    [self.tableView reloadData];
}

- (void)requestDatasource {
//    self.datasource = @[@[@{@"title":ASLocalizedString(@"置顶该消息"), @"state":@(self.isZhiding)}],
//                        @[@{@"title":ASLocalizedString(@"清空聊天记录")}]].mutableCopy;
    self.datasource = @[@[@{@"title":ASLocalizedString(@"置顶该消息"), @"state":@(self.isZhiding)}],
                        @[@{@"title":ASLocalizedString(@"清空聊天记录")}],
                        @[@{@"title":ASLocalizedString(@"投诉")}]].mutableCopy;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 50;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 20;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.datasource.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [self.datasource[section] count];
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *sectionHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kBDScreenWidth, 20)];
    sectionHeaderView.backgroundColor = [UIColor clearColor];
    return sectionHeaderView;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    BDChatSetTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"chatSet" forIndexPath:indexPath];
    cell.textLabel.text = [self.datasource[indexPath.section][indexPath.row] objectForKey:@"title"];
    if ([self.datasource[indexPath.section][indexPath.row] objectForKey:@"state"]) {
        UISwitch *aSwitch = [[UISwitch alloc] init];
        aSwitch.on = [[self.datasource[indexPath.section][indexPath.row] objectForKey:@"state"] boolValue];
        cell.accessoryView = aSwitch;
        [[aSwitch rac_signalForControlEvents:UIControlEventValueChanged] subscribeNext:^(__kindof UIControl * _Nullable x) {
            if (indexPath.section == 0 && indexPath.row == 0) {
                NSString *zhidingSearchPath = [DocumentPath stringByAppendingPathComponent:@"zhidingSearch.plist"];
                NSMutableArray *array = [NSMutableArray arrayWithContentsOfFile:zhidingSearchPath];
                if (self.isZhiding == NO) {
                    [array addObject:((JMSGUser *)_conversation.target).username];
                }else {
                    [array removeObject:((JMSGUser *)_conversation.target).username];
                }
                self.isZhiding = !self.isZhiding;
                if ([array writeToFile:zhidingSearchPath atomically:YES]) {
                    // BDLog(ASLocalizedString(@"swith修改成功了哦"));
                }
            }else if (indexPath.section == 0 && indexPath.row == 1) {
                [(JMSGUser *)_conversation setIsNoDisturb:!self.isMiandarao handler:^(id resultObject, NSError *error) {
                    if (error) {
                        aSwitch.on = !aSwitch.on;
                    }else{
                        //更新数据
                    }
                }];
            }
        }];
    }else{
        cell.accessoryView = nil;
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 1) {
        [LPActionSheet showActionSheetWithTitle:nil
                              cancelButtonTitle:ASLocalizedString(@"取消")destructiveButtonTitle:ASLocalizedString(@"清空聊天记录")otherButtonTitles:nil handler:^(LPActionSheet *actionSheet, NSInteger index) {
                                  if (index == -1) {
//                                      EMMessage *lastMessage = [self.conversation latestMessage];
//                                      long long timeInterval = 0;
//                                      if (lastMessage) {
//                                          timeInterval = lastMessage.timestamp;
//                                      }else {
//                                          timeInterval = [[NSDate dateWithTimeIntervalSinceNow:0] timeIntervalSince1970] * 1000;
//                                      }
//                                      [self.conversation deleteAllMessages:nil];
//                                      //这里插入消息
//                                      NSString *fromStr = [EMClient sharedClient].currentUsername;
//                                      NSString *text = @"";
//                                      EMTextMessageBody *body = [[EMTextMessageBody alloc] initWithText:text];
//
//                                      EMMessage *message = [[EMMessage alloc] initWithConversationID:self.conversation.conversationId from:fromStr to:self.conversation.conversationId body:body ext:@{@"messageSpecialType":@"empty"}];
//                                      message.chatType = EMChatTypeChat;
//                                      message.timestamp = timeInterval;
//                                      [self.conversation insertMessage:message error:nil];
//                                      [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshChatData" object:nil];
//                                      [MBManager showBriefAlert:ASLocalizedString(@"清空聊天记录成功")clickHidden:YES clickBlock:nil];
                                  }
                              }];
        
    }else if (indexPath.section == 2) {
        BDComplaintsViewController *complaintsVC = [[BDComplaintsViewController alloc] init];
        complaintsVC.user_id = [((JMSGUser *)_conversation.target).username stringByReplacingOccurrencesOfString:@"beboy_" withString:@""];
        [self.navigationController pushViewController:complaintsVC animated:YES];
    }
}

- (UITableView *)tableView{
    if (!_tableView) {
        self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, kBDTopHeight, kBDScreenWidth, kBDScreenHeight - kBDTopHeight) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        [_tableView registerClass:[BDChatSetTableViewCell class] forCellReuseIdentifier:@"chatSet"];
        _tableView.tableHeaderView = [self customHeaderView];
        _tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.separatorInset = UIEdgeInsetsZero;
        [self.view addSubview:_tableView];
    }
    return _tableView;
}

- (UIView *)customHeaderView{
    UIView *headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kBDScreenWidth, 110)];
    headView.backgroundColor = [UIColor whiteColor];
    
    UIImageView *coverImageView = [[UIImageView alloc] init];
    coverImageView.size = CGSizeMake(50, 50);
    coverImageView.top = 20;
    coverImageView.left = 15;
    coverImageView.layer.masksToBounds = YES;
    coverImageView.layer.cornerRadius = coverImageView.width / 2.0;
    coverImageView.userInteractionEnabled = YES;
    
    [coverImageView sd_setImageWithURL:[NSURL URLWithString:((JMSGUser *)_conversation.target).avatar] placeholderImage:[UIImage imageNamed:@"avatar"]];
    [headView addSubview:coverImageView];
    
    UITapGestureRecognizer *tapGR = [[UITapGestureRecognizer alloc] init];
    [coverImageView addGestureRecognizer:tapGR];
    [[tapGR rac_gestureSignal] subscribeNext:^(__kindof UIGestureRecognizer * _Nullable x) {
        BDUserInfoViewController *userVC = [[BDUserInfoViewController alloc] initWithUserID:[[((JMSGUser *)_conversation.target).username stringByReplacingOccurrencesOfString:@"beboy_" withString:@""] integerValue] isFollow:NO guanzhuBlock:nil];
        [self.navigationController pushViewController:userVC animated:YES];
    }];
    
    UILabel *nickLabel = [[UILabel alloc] init];
    nickLabel.text = ((JMSGUser *)_conversation.target).nickname;
    nickLabel.textColor = [UIColor colorWithHexString:@"#808080"];
    nickLabel.font = [UIFont systemFontOfSize:13];
    nickLabel.textAlignment = NSTextAlignmentCenter;
    nickLabel.size = CGSizeMake(coverImageView.width, 14);
    nickLabel.top = coverImageView.bottom + 8;
    nickLabel.centerX = coverImageView.centerX;
    [headView addSubview:nickLabel];
    
    UIButton *addButton = [UIButton buttonWithType:UIButtonTypeCustom];
    addButton.size = CGSizeMake(50, 50);
    [addButton setImage:[UIImage imageNamed:@"message_set_add"] forState:UIControlStateNormal];
    addButton.top = coverImageView.top;
    addButton.left = coverImageView.right + 30;
    BDUserModel *selfUser = [BDUserModel getCurrentUser];
    if (selfUser.user_id != [[((JMSGUser *)_conversation.target).username stringByReplacingOccurrencesOfString:@"beboy_" withString:@""] integerValue]) {
        [headView addSubview:addButton];
    }
    
    [[addButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        BDGroupChooseViewController *groupChooseVC = [[BDGroupChooseViewController alloc] init];
        groupChooseVC.startArray = @[((JMSGUser *)_conversation.target).username];
        groupChooseVC.chooseType = BDChatChooseTypeCreat;
        [self presentViewController:[[UINavigationController alloc] initWithRootViewController:groupChooseVC] animated:YES completion:nil];
    }];
    
    return headView;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
